<template>
  <div class="directorys-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 面包屑导航页头 -->
        <el-page-header
          v-if="test"
          @back="goBack"
          style="
            margin-bottom: 30px;
            color: #606266;
            font-size: 14px;
            position: relative;
          "
        >
        </el-page-header>
        <el-breadcrumb
          v-if="test"
          separator-class="el-icon-arrow-right"
          style="position: absolute; left: 10%; top: 11%"
        >
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ name }}</el-breadcrumb-item>
          <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 分割线 -->
        <el-divider v-if="test"></el-divider>
        <el-row>
          <el-form
            label-width="80px"
            :model="requestParameters"
            class="demo-form-inline"
            ref="requestParameters"
            :rules="requestParametersRules"
          >
            <el-col :span="5">
              <el-form-item label="目录名称">
                <el-input
                  v-model="requestParameters.directoryName"
                  placeholder="目录名称"
                  porp="directoryName"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="状态">
                <el-select
                  v-model="requestParameters.state"
                  placeholder="请选择"
                  porp="state"
                >
                  <el-option
                    v-for="item in stateStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item style="position: relative" label-width="10px">
                <el-button
                  class="el-button el-button--default el-button--small"
                  size="small"
                  @click="ondel"
                  >清除</el-button
                >
                <el-button type="primary" size="small" @click="handleFilter"
                  >搜索</el-button
                >
              </el-form-item>
            </el-col>
          </el-form>
          <!--面包屑  -->
          <el-col :span="2">
            <el-button
              type="text"
              v-if="test"
              @click="$router.push('list')"
              icon="el-icon-back"
              style="color: #409eff; font-size: 16px"
              >返回学科</el-button
            >
          </el-col>
          <el-col :span="2">
            <el-button
              class="el-button el-button--success el-button--small"
              size="small"
              type="button"
              icon="el-icon-edit"
              @click="add"
              >新增目录</el-button
            >
          </el-col>
        </el-row>
        <!-- 数据记录 -->
        <el-alert
          style="margin-bottom: 10px"
          :title="countsText"
          type="info"
          show-icon
          :closable="false"
        >
        </el-alert>
        <!-- 数据列表 -->
        <el-table :data="list" border style="width: 100%" v-loading="loading">
          <el-table-column fixed type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科">
          </el-table-column>
          <el-table-column prop="directoryName" label="目录名称">
          </el-table-column>
          <el-table-column prop="username" label="创建者">
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="addDate" label="创建日期">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | formatDate('YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totals" label="面试题数量"> </el-table-column>
          <el-table-column prop="state" label="状态">
            <template slot-scope="scope">
              <span v-if="scope.row.state == 1">已启用</span>
              <span v-else>已禁用</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleStatus(scope.row)"
              >
                <span v-if="scope.row.state == 0">启用</span>
                <span v-else>禁用</span>
              </el-button>
              <el-button
                @click="emit(scope.row)"
                type="text"
                size="small"
                :disabled="scope.row.state == 0"
                >修改</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="del(scope.row.id)"
                :disabled="scope.row.state == 0"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- current-page 当前的页码值 -->
        <!-- page-size 当前，每页显示多少条数据 -->
        <!-- total 总数据条数 -->
        <!-- page-sizes 数组，可选的分页条数 -->
        <el-pagination
          style="margin: 10px"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange11"
          :current-page="currentPage"
          :page-sizes="[5, 8, 10, 20]"
          :page-size="100"
          layout="->, prev, pager, next, jumper,sizes"
          :total="counts"
        >
        </el-pagination>
      </el-card>

      <!--新增目录通过学科弹出层  -->
      <el-dialog
        v-if="test"
        width="25%"
        :title="titleText"
        :visible="showdialog"
        @close="closeDialog"
      >
        <el-form :model="form" :rules="subFormRules" ref="subFormRef">
          <el-form-item
            label="目录名称"
            label-width="80px"
            prop="directoryName"
          >
            <el-input
              v-model="form.directoryName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="subAdd">确 认</el-button>
        </div>
      </el-dialog>

      <!-- 新增目录弹出层 -->
      <el-dialog
        v-else
        width="25%"
        :title="titleText"
        :visible="showdialog"
        @close="closeDialog"
      >
        <el-form
          :model="form"
          label-width="80px"
          :rules="subFormRules"
          ref="subFormRef"
        >
          <el-form-item label="所属学科" prop="subjectID" size="medium">
            <el-select
              v-model="form.subjectID"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in subjectNameList"
                :key="index"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="目录名称"
            label-width="80px"
            prop="directoryName"
          >
            <el-input
              v-model="form.directoryName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="subAdd">确 认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { status as stateStatus } from '@/api/hmmm/constants'
import { list, add, remove, update } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'
export default {
  data () {
    return {
      loading: false,
      // 获取到的数据
      list: [],
      // 弹出框
      showdialog: false,
      // 总记录数
      counts: 0,
      // 记录数
      countsText: '',
      // 弹出框数据
      form: {
        subjectID: '',
        directoryName: ''
      },
      // 弹出框标题
      titleText: '添加目录',
      // 表单的验证规则对象
      subFormRules: {
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '文章标题的长度为1-15个字符',
            trigger: 'blur'
          }
        ],
        subjectID: [{ required: true, message: '请选择', trigger: 'blur' }]
      },
      requestParametersRules: {
        directoryName: [
          { message: '请输入目录名称', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '文章标题的长度为1-15个字符',
            trigger: 'blur'
          }
        ]
      },
      currentPage: 1,
      requestParameters: {
        page: 1,
        pagesize: 5
      },
      subjectNameList: [],
      status: ''
    }
  },
  created () {
    this.getList()
    this.getSubList()

    // this.getSubTest()
  },
  computed: {
    stateStatus () {
      return stateStatus
    },
    // 获取到请求头数据
    test () {
      return +this.$route.query.id
    },
    // 获取到请求头数据
    name () {
      return this.$route.query.name
    }
  },
  methods: {
    // 获取数据
    async getList () {
      this.loading = true
      // 如果有学科ID 将学科ID传给form
      if (this.test) {
        this.requestParameters.subjectID = this.test
        this.form.subjectID = this.test
      }
      const { data: res } = await list(this.requestParameters)
      // console.log(res.items)
      // 获取到的数据储存
      this.list = res.items
      // 数据总记录数
      this.counts = res.counts
      this.countsText = `数据一共${this.counts}条`
      this.loading = false
    },
    // 获取学科简单列表
    async getSubList () {
      const { data: res } = await simple()
      // console.log(res)
      // 把所属学科赋值给弹出框学科
      this.subjectNameList = res
    },
    // 弹出框添加
    subAdd () {
      this.$refs.subFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 有id就是修改
        if (this.form.id) {
          await update(this.form)
          this.$message.success('修改目录成功！')
        } else {
          // 添加请求
          const res = await add(this.form)
          // console.log(res)
          if (res.status !== 200) return this.$message.error('添加目录失败！')
          this.$message.success('添加目录成功！')
        }
        // 重新渲染
        this.getList()
        // 调用
        this.closeDialog()
      })
    },
    // 关闭弹出框并重置表单
    closeDialog () {
      // 关闭弹出框
      this.showdialog = false
      // 重置表单
      this.$refs.subFormRef.resetFields()
      // 重置form数据
      this.form = {
        subjectID: '',
        directoryName: ''
      }
    },
    // 删除目录
    del (id) {
      // console.log(id)
      this.$confirm('此操作将永久删除用户 ' + ', 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        await remove({ id })
          // console.log(res)
          .then((response) => {
            this.$message.success('成功删除了目录' + '!')
            // 重新渲染
            this.getList()
          })
          .catch((response) => {
            this.$message.error('删除失败!')
          })
      }).catch(_ => _)
      // 判断页码值是否需要自减
      if (this.list.length === 1 && this.requestParameters.page > 1) {
        this.requestParameters.page--
      }
    },
    // 修改目录
    async emit (id) {
      this.titleText = '修改目录'
      // 打开弹出层
      this.showdialog = true
      // console.log(id)
      const { config: res } = await update(id)
      // 获取到点击修改的单项数据
      // console.log(JSON.parse(res.data))
      const data = JSON.parse(res.data)
      // 将数据赋值给表单
      // this.form.subjectID = data.subjectID
      // this.form.directoryName = data.directoryName
      this.form = data
    },
    // 每页显示多少条数据发生变化的时候，会触发这个函数
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      // 1. 为 pagesize 赋新值
      this.requestParameters.pagesize = val
      // 2. 根据最新的 重新渲染 函数
      this.getList()
    },
    // 页码值变化，会触发下面的函数
    handleCurrentChange11 (val) {
      // console.log(`当前页: ${val}`)
      // 1. 为 page 赋新值
      this.requestParameters.page = val
      // 如果当前页数组长度0,页码值--
      // 样式展现默认第几页数据
      this.currentPage = val
      // 2. 根据最新的 重新调用渲染，获取对应那一页的数据
      this.getList()
    },
    // 状态
    handleStatus (val) {
      // this.status = val.state
      // console.log(val)
      // console.log(val.id)
      // console.log(val.state)
      if (val.state === 1) {
        val.state = 0
        this.status = '禁用'
      } else {
        val.state = 1
        this.status = '启用'
      }
    },
    // 搜索信息
    handleFilter () {
      // this.status = this.requestParameters.status
      this.requestParameters.page = 1
      this.getList(this.requestParameters)
    },
    // 清除
    ondel () {
      // console.log('del')
      // this.$refs.requestParameters.resetFields()
      this.requestParameters = {
        page: 1,
        pagesize: 5
      }
      // 默认跳转
      this.currentPage = 1
      // 重新获取列表
    },
    add () {
      this.showdialog = true
      // 点击添加目录，标题
      this.titleText = '添加目录'
    },
    // 面包屑导航页头回归
    goBack () {
      this.$router.replace('/subjects/list')
    }
  }
  // 监听路由跳转重新渲染页面
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-table__header {
  color: #909399;
}
</style>
